package org.kernely.stream.messageFilter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.kernely.stream.service.StreamFilter;

public class ImageFilter implements StreamFilter{

	public String applyFilter(String messageToFilter) {
		// TODO : Improve and correct bug replacement regex
		
		String txt = messageToFilter;
		String regexp = "([^=\"])(((f|ht){1}tp[s]?:\\/\\/|(?<!\\S)www\\.)[-a-zA-Z0-9@:%_\\+.~#?&\\/\\/=]+(.jpg|.png|.gif))";

		Pattern p = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(txt);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			String link = m.group(2);
			if(!link.startsWith("http://")){
				link = "http://" + link;
			}
			m.appendReplacement(sb, "<br/><img style=\"max-width:280px;\" src=\"" + link + "\" alt=\""+ link +"\"/><br/>");
		}
		m.appendTail(sb);
		
		return sb.toString();
	}

}